package org.nmgyjt.springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nmgyjt.springboot.entity.exception.BizException;
import org.nmgyjt.springboot.entity.sms.*;
import org.nmgyjt.springboot.utils.HttpUtils;
import org.nmgyjt.springboot.utils.HttpsService;
import org.nmgyjt.springboot.utils.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("messageSmsAccountService")
@Transactional
public class SendSMSServiceImpl {

    protected static final Logger log = LogManager.getLogger(SendSMSServiceImpl.class);
    private static String NMGYJT_SMS_IP = "http://10.8.12.109:18777";
    private static String NMGYJT_TOKEN_URI = "/authorization-server/oauth/token";
    private static String NMGYJT_SMS_URI = "/bus/third/msg/send";
    private static String TEMPLATE_NAME = "spring.nmgyjt.sms.";
    private static String NMGYJT_SMS_CLIENT_ID = "yufu";
    private static String NMGYJT_SMS_CLIENT_SECRET = "Yufu@123";
    @Autowired
    PropertiesUtil propertiesUtil;


    public NMGYJTSMSTokenResponse getToken() {
        //配置请求头参数
        List<BasicNameValuePair> headers = new ArrayList();
        headers.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
        headers.add(new BasicNameValuePair("Authorization", "[token_type] [access_token]"));


        //配置请求参数
        List<BasicNameValuePair> params = new ArrayList();
        params.add(new BasicNameValuePair("grant_type", "client_credentials"));
        params.add(new BasicNameValuePair("client_id", NMGYJT_SMS_CLIENT_ID));
        params.add(new BasicNameValuePair("client_secret", NMGYJT_SMS_CLIENT_SECRET));

        String tokenResponseStr = HttpsService.post(NMGYJT_SMS_IP + NMGYJT_TOKEN_URI, params, headers);
        log.info("get token from " + NMGYJT_TOKEN_URI + ", token data is >>>>" + tokenResponseStr);

        return JSONObject.parseObject(tokenResponseStr, NMGYJTSMSTokenResponse.class);

    }


    public String sendMS(YuFuMSSendEntity sendObject) {
        log.info("getToken  >>  start");
        NMGYJTSMSTokenResponse tokenObject = getToken();

        log.info("getToken  >>  success");
        if (null == tokenObject || StringUtils.isEmpty(tokenObject.getAccessToken())) {
            log.error("get token exception >> 接口访问权限异常,请联系管理员");
            throw new BizException("接口访问权限异常,请联系管理员");
        }

        log.info("getToken  >> success");
        HashMap<String, String> headerParams = new HashMap<>();
        JSONObject bodyParams = new JSONObject();

        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + tokenObject.getAccessToken());
        //headerParams.put("Authorization", "bearer ");
        bodyParams.put("sysChannelCode", "CLOUD_SMS");
        bodyParams.put("thirdSystemCode", "YUFU");
        bodyParams.put("buzType", 201);

        List<String> phoneNums = replacePhoneNum(sendObject);

        ArrayList<String> sendNum = new ArrayList<>();
        List<YuFuMSSendStatusSet> sendStatusSets = new ArrayList<>();
        YuFuSendMsgResponse yuFuSendMsgResponse = new YuFuSendMsgResponse();
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        if (null != phoneNums && phoneNums.size() > 0) {
            phoneNums.forEach(num -> {
                sendNum.clear();
                bodyParams.put("detail", getMSContent(sendObject));
                sendNum.add(num);
                bodyParams.put("userIds", sendNum);

                log.info(bodyParams);
                String clientPostRes = HttpUtils.sendHttpPost(NMGYJT_SMS_IP + NMGYJT_SMS_URI, bodyParams, headerParams);

                log.info("sendSms {}", clientPostRes);
                NMGYJTSMSResponse nmgyjtsmsResponse = JSONObject.parseObject(clientPostRes, NMGYJTSMSResponse.class);
                if (null != nmgyjtsmsResponse) {
                    if ("0000".equals(nmgyjtsmsResponse.getCode()))
                        yuFuSendMsgResponse.setCode(0);
                    yuFuSendMsgResponse.setMessage(nmgyjtsmsResponse.getMesg());
                    yuFuSendMsgResponse.setValue(nmgyjtsmsResponse.getData());
                    YuFuMSSendStatusSet statusSet = new YuFuMSSendStatusSet();
                    statusSet.setPhoneNumber(num);
                    statusSet.setSendNum(nmgyjtsmsResponse.getData().getMsgGroup());
                    sendStatusSets.add(statusSet);
                    ;
                }
            });
        }
        objectObjectHashMap.put("sendStatusSet", sendStatusSets);
        yuFuSendMsgResponse.setValue(objectObjectHashMap);
        log.info("sms response data {}", yuFuSendMsgResponse);
        return JSONObject.toJSONString(yuFuSendMsgResponse);
    }


    public NMGYJTMSDetail getMSContent(YuFuMSSendEntity sendObject) {

        //  YuFuMSTemplateEnum yuFuMSTemplateEnum = YuFuMSTemplateEnum.fromType(sendObject.getType().toUpperCase());
        String content = propertiesUtil.propLoad(TEMPLATE_NAME + sendObject.getType().toLowerCase());
        if (null == content) {
            log.error("短信模板获取异常,idaas发送短信失败!");
            throw new BizException("短信模板获取异常,idaas发送短信失败!");
        }
        if (sendObject.getTemplateParamSet().size() == 1) {
            content = content.replace("{1}", sendObject.getTemplateParamSet().get(0));
        } else if (sendObject.getTemplateParamSet().size() == 2) {
            content = content.replace("{1}", sendObject.getTemplateParamSet().get(0)).replace("{2}", sendObject.getTemplateParamSet().get(1));
        } else if (sendObject.getTemplateParamSet().size() == 3) {
            content = content.replace("{1}", sendObject.getTemplateParamSet().get(0)).replace("{2}", sendObject.getTemplateParamSet().get(1)).replace("{3}", sendObject.getTemplateParamSet().get(2));
        } else if (sendObject.getTemplateParamSet().size() == 4) {
            content = content.replace("{1}", sendObject.getTemplateParamSet().get(0)).replace("{2}", sendObject.getTemplateParamSet().get(1)).replace("{3}", sendObject.getTemplateParamSet().get(2)).replace("{4}", sendObject.getTemplateParamSet().get(3));
        } else if (sendObject.getTemplateParamSet().size() == 5) {
            content = content.replace("{1}", sendObject.getTemplateParamSet().get(0)).replace("{2}", sendObject.getTemplateParamSet().get(1)).replace("{3}", sendObject.getTemplateParamSet().get(2)).replace("{4}", sendObject.getTemplateParamSet().get(3)).replace("{5}", sendObject.getTemplateParamSet().get(4));
        } else if (sendObject.getTemplateParamSet().size() == 6) {
            content = content.replace("{1}", sendObject.getTemplateParamSet().get(0)).replace("{2}", sendObject.getTemplateParamSet().get(1)).replace("{3}", sendObject.getTemplateParamSet().get(2)).replace("{4}", sendObject.getTemplateParamSet().get(3)).replace("{5}", sendObject.getTemplateParamSet().get(4)).replace("{6}", sendObject.getTemplateParamSet().get(5));
            if (content.contains("@旧密码@")) {
                content = content.replace("初始密码:@旧密码@。", "");
            }
        } else {
            log.error("短信模板参数异常,idaas发送短信失败");
            throw new BizException("短信模板参数异常,idaas发送短信失败");
        }
        return new NMGYJTMSDetail(content);

    }

    public List<String> replacePhoneNum(YuFuMSSendEntity sendObject) {
        List<String> phoneNumSet = sendObject.getPhoneNumSet();

        Pattern p1 = Pattern.compile("^((\\+{0,1}86){0,1})1[0-9]{10}");
        List<String> phoneNums = new ArrayList<>();
        if (null != phoneNumSet && phoneNumSet.size() > 0) {
            phoneNumSet.stream().forEach(p -> {
                Matcher m1 = p1.matcher(p);
                if (m1.matches()) {

                    Pattern p2 = Pattern.compile("^((\\+{0,1}86){0,1})");
                    Matcher m2 = p2.matcher(p);
                    StringBuffer sb = new StringBuffer();
                    while (m2.find()) {
                        m2.appendReplacement(sb, "");
                    }
                    m2.appendTail(sb);
                    phoneNums.add(sb.toString());
                } else {
                    log.error("The format of phoneNum " + p + "  is not correct!Please correct it");
                }

            });
        }

        log.info(new Date(System.currentTimeMillis()) + ",send sms phone list:" + phoneNums);
        return phoneNums;

    }


}
